<script setup lang="ts">
import { 
  RequestPath, 
  startRequest
} from '../base/RequestWork';
import type { 
  OperationalResponseData, 
  OperationalItemData,
  CategroyResponseData, 
  GoodsItemData, 
  GoodsResponseData
} from '../base/RequestWork';
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import {useRouter} from 'vue-router'
let router = useRouter()

// 轮播位绑定的数据
let datas = ref()

// 类别数据源
let categoryList = ref()
// 用户当前选中的类别index，默认选中第1个类别
let currentSelectedCategoryIndex = ref(0)

// 商品数据
let goods = ref()
// 分页参数
let offset = 0
const limit = 4
// 是否有更多数据
let hasMore = ref(true)
// 组件挂载时的生命周期函数
onMounted(() => {
  // 请求运营位数据，只获取启用状态的运营位
  startRequest(RequestPath.operationalGet, 'get', { 'status': 1 })
    .then((response) => {
      const data = response.data as OperationalResponseData;  // 移除 .data
      datas.value = data.datas ?? [];
    })
    .catch((error) => {
      ElMessage.error({
        message: error.response?.data?.error || error.message || '加载运营位数据失败'
      });
    });
    loadCategory(()=>{
        // 这里加载商品数据
        loadGoods(categoryList.value[currentSelectedCategoryIndex.value].id)
    })
});
// 请求类别数据
function loadCategory(cb:()=>void) {
    startRequest(RequestPath. categoryListGet, 'get', {}).then((response)=>{
        let data = response.data as CategroyResponseData  // 移除 .data
        categoryList.value = data.datas ?? []
        // 请求完成后，进行回调函数的执行
        cb()
    }).catch((error)=>{
        ElMessage.error({
            message: error.response?.data?.error || error.message || '加载类别数据失败'
        })
    })
}
// 请求商品列表数据
function loadGoods(cid: number) {
    startRequest(RequestPath.goodsListGet, 'get', {
        offset,
        limit,
        cid
    }).then((response)=>{
        let data = response.data as GoodsResponseData  // 移除 .data
        let datas:GoodsItemData[] = goods.value ?? []
        // 判断返回的数据量是否小于limit，小于则表明没有更多数据了
        hasMore.value = (data.datas ?? []).length >= limit
        // 将返回的数据追加到数据源中
        datas.push(...(data.datas ?? []))
        goods.value = datas
        // 对offset进行设置
        offset = datas.length
    }).catch((error)=>{
        ElMessage.error({
            message: error.response?.data?.error || error.message || '加载商品数据失败'
        })
    })
}

// 点击某个运营位的方法，后续实现实现具体功能
function clickItem(item: OperationalItemData) {
  router.push({
    // 拼接完整路由（修复语法错误，处理类似 'goods/1' 格式的URI）
    path: `/home${item.uri}`
  });
}
// 切换类别
function categoryClick(index: number) {
    currentSelectedCategoryIndex.value = index
    // 切换类别，刷新商品列表
    offset = 0
    goods.value = []
    loadGoods(categoryList.value[index].id)
}
// 跳转到商品详情页
function goDetail(item: GoodsItemData) {
    router.push({
        name: 'goodsDetail',
        params: {id: item.id}
    })
}

</script>

<template>
    <div class="operational">
        <!-- 轮播组件 -->
        <el-carousel indicator-position="outside" height="auto">
            <el-carousel-item v-for="item in datas" :key="item.id" style="height: 400px">
                <div class="content" @click="clickItem(item)">
                    <el-image style="width: 100%; height: 400px;" :src="item.cover" fit="fill"/>
                    <div class="bottom-bar">
                        {{ item.content }}
                    </div>
                </div>
            </el-carousel-item>
        </el-carousel>
        <!-- 商品列表 -->
        <div>
            <div style="width: 100%; text-align: center; height: 50px; line-height: 50px; font-size: 30px; color: darkblue;">~ 为您推荐 ~</div>
            <div class="header-bar">
                <div v-for="(ca, index) in categoryList" :key="ca.id" :class="currentSelectedCategoryIndex == index ? 'category-item-title-selected' : 'category-item-title-normal'" @click="categoryClick(index)">
                   <div style="font-size: 30px; margin-bottom: 5px;">{{ ca.name }}</div>
                   <div>{{ ca.description }}</div>
                </div>
            </div>
            <div class="goods_list">
                <div v-for="item in goods" :key="item.id" class="goods_item " @click="goDetail(item)">
                    <div style="width: 200px; height: 150px; overflow: hidden; ">
                        <el-image style="width: 100%; height: 100%;" :src="item.image" fit="fill" />
                    </div>
                    <div style="width: 100%; height: 150px; background-color: #eeeeee; position: relative;">
                        <div style="padding: 5px;"><span class="brend">{{ item.brand }}</span>{{ item.name }}</div>
                        <div style="padding-left: 5px;padding-right: 5px; font-size: 13px; color: gray;">{{ item.description }}</div>
                        <div style="padding: 5px; font-size: 18px; color: red;">惊喜价:{{ item.price }}￥ <span style="color: gray; font-size: 11px;">原价:{{ item.discounted_price }}￥</span></div>
                        <el-tag style="position: absolute; bottom: 10px; left:10px" :type="item.status == 1 ? 'success' : 'error'">{{ item.status == 1 ? '售卖中' : '已下架' }}</el-tag>
                    </div>
                </div>
            </div>
            <div v-show="hasMore" style="width: 100%; text-align: center; margin-top: 15px; color: grey;" @click="loadGoods(categoryList[currentSelectedCategoryIndex].id)">点击加载更多</div>
        </div>
    </div>
</template>

<style>

.operational {
    margin-top: 20px;
}

.content {
    background-color: azure;
    height: 400px;
}
.bottom-bar {
    background-color: #00000077;
    position: fixed;
    height: 40px;
    bottom: 0px;
    width: 100%;
    color: white;
    line-height: 40px;
    padding-left: 20px;
}

.header-bar {
    display: flex;
    flex-direction: row;
    width: 100%;
}

.category-item-title-selected {
    color: red;
    width: 300px;
    text-align: center;
}

.category-item-title-normal {
    color: black;
    width: 300px;
    text-align: center;
}

.goods_list {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    margin-top: 10px;
}

.goods_item {
    width: 200px;
    height: 300px;
    margin: 10px;
    border-radius: 15px;
    overflow: hidden;
}

.brend {
    background-color: red;
    color: white;
    font-size: 12px;
    padding: 2px;
    border-radius: 4px;
    margin-right: 5px;
}

</style>